//
//  XS_PlanSubVC.swift
//  XueDao
//
//  Created by Mac on 2020/12/14.
//

import UIKit
import JXSegmentedView
import CVCalendar

class XS_PlanSubVC: XS_BaseVC {

    @IBOutlet weak var collectionView: UICollectionView!
    var courseArray : [XS_CourseItemModel] = []
    var courseRecordModel = XS_CourseItemM()
    
    var weekArray : [XS_WeekItemModel] = []
    
    var goalModel : XS_GoalCertResponseModel?
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        collectionView.register(UINib.init(nibName: "XS_PlanImageCell", bundle: Bundle.main), forCellWithReuseIdentifier: "XS_PlanImageCell")
        collectionView.register(UINib.init(nibName: "XS_PlanTodayItemCell", bundle: Bundle.main), forCellWithReuseIdentifier: "XS_PlanTodayItemCell")
        collectionView.register(UINib.init(nibName: "XS_GoalCertCell", bundle: Bundle.main), forCellWithReuseIdentifier: "XS_GoalCertCell")
        collectionView.register(XS_PlanCalendarCell.classForCoder(), forCellWithReuseIdentifier: "XS_PlanCalendarCell")
        
        collectionView.register(UINib.init(nibName: "XS_PlanTodayHeaderView", bundle: Bundle.main), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "XS_PlanTodayHeaderView")
        collectionView.register(UINib.init(nibName: "XS_PlanGoalCertHeaderView", bundle: Bundle.main), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "XS_PlanGoalCertHeaderView")
        
        collectionView.delegate = self
        collectionView.dataSource = self
        
//        collectionView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: .bottomHeight + 16, right: 0)
        collectionView.mj_header = MJRefreshNormalHeader.init(refreshingTarget: self, refreshingAction: #selector(headerRefresh))
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        headerRefresh()
    }
    
    @objc func headerRefresh(){
        requestCourseData()
        let date = Date.init()
        let dateFormatter = DateFormatter.init()
        dateFormatter.dateFormat = "yyyy-MM-dd"
        requestCourseTodayData(date: dateFormatter.string(from: date))
        requestGoalCertData()
        requestCourseWeekData()
        perform(#selector(endHeaderRefresh), with: self, afterDelay: 0.5)
    }
    
    @objc func endHeaderRefresh(){
//        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "ShowTodayNoti"), object: nil)
        collectionView.mj_header?.endRefreshing()
    }

    func requestCourseTodayData(date : String){
//        /plan/queryUserLearnCurriculumToday
        XS_NetWork.requestJson("/plan/queryUserLearnCurriculumToday", parameters: ["date":date])
            .mapModels(type: XS_CourseItemModel.self) // 返回 模型数组 和原始数据
            .subscribe(onNext: { array, resp in
                self.courseArray = array
                self.collectionView.reloadData()
            }).disposed(by: disposeBag)
    }
    
    
    func requestCourseWeekData(){
//        /plan/queryUserLearnCurriculumToday
        XS_NetWork.requestJson("/plan/queryUserLearnStateOnThisWeek")
            .mapModels(type: XS_WeekItemModel.self) // 返回 模型数组 和原始数据
            .subscribe(onNext: { array, resp in
                self.weekArray = array
                self.collectionView.reloadData()
            }).disposed(by: disposeBag)
    }
    
    func requestCourseData(){
        XS_NetWork.requestJson("/curriculum/queryPlanCurriculum")
            .mapModels(type: XS_CourseItemModel.self) // 返回 模型数组 和原始数据
            .subscribe(onNext: { [weak self] array, resp in
                self?.courseRecordModel.records = array
                self?.collectionView.reloadData()
            }).disposed(by: disposeBag)
    }
    
    func requestGoalCertData(){
        XS_NetWork.requestJson("/plan/queryGoalCertificate")
            .mapModel(type: XS_GoalCertResponseModel.self) // 返回 模型对象 和原始数据
            .subscribe(onNext: { model, resp in
                self.goalModel = model
                self.collectionView.reloadData()
            }).disposed(by: disposeBag)
    }
}

extension XS_PlanSubVC : UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 4
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        switch section {
        case 0:
            return 1
        case 1:
            return 1
        case 2:
            return courseArray.count > 0 ? courseArray.count : 1
        case 3:
            return 1
        default:
            return 0
        }
    }
    
    /// 添加空白页
    private func addBlankPageView(superView: UIView, data: Array<Any>) {
        if data.count > 0 {
            XD_BlankPageView.hiddenBlankPageView(superView: superView)
        } else {
            let blankPageView = XD_BlankPageView()
            blankPageView.blankPage(imgName: "缺省页_暂无内容", detailStr: "暂无内容~", bottomDetailStr: "")
            blankPageView.frame = CGRect.init(x: 0, y: -84, width: superView.frame.size.width, height: superView.frame.size.height + 84)
            
            superView.addSubview(blankPageView)
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        switch indexPath.section {
        case 0:
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "XS_PlanImageCell", for: indexPath)
            return cell
        case 1:
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "XS_PlanCalendarCell", for: indexPath) as! XS_PlanCalendarCell
            cell.delegate = self
            if weekArray.count > 0 {
                cell.dataArray = weekArray
            }
            return cell
        case 2:
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "XS_PlanTodayItemCell", for: indexPath) as! XS_PlanTodayItemCell
            if courseArray.count != 0 {
                cell.model = courseArray[indexPath.item]
            }
            addBlankPageView(superView: cell, data: courseArray)
            cell.delegate = self
            return cell
        case 3:
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "XS_GoalCertCell", for: indexPath) as! XS_GoalCertCell
            if courseRecordModel != nil {
                cell.model = courseRecordModel
            }
            addBlankPageView(superView: cell, data: courseRecordModel.records)
            
            cell.delegate = self
            return cell
        default:
            return UICollectionViewCell.init()
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        if indexPath.section == 2 {
            let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "XS_PlanTodayHeaderView", for: indexPath) as! XS_PlanTodayHeaderView
            headerView.delegate = self
            return headerView
        }else if indexPath.section == 3{
            let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "XS_PlanGoalCertHeaderView", for: indexPath) as! XS_PlanGoalCertHeaderView
            if goalModel != nil {
                headerView.sayLabel.text = goalModel?.saying
            }
            return headerView
        }
        return UICollectionReusableView.init()
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if indexPath.section == 2 {
            if courseArray.count == 0 {
                return
            }
            let type = self.courseArray[indexPath.item].curriculumType
            let id = self.courseArray[indexPath.item].id
//            if type == "seriesCurriculum" || type == "notSeriesCurriculum" {
                //线上课
                let vc = XS_KeChengVC()
                vc.id = id
                navigationController?.pushViewController(vc, animated: true)
//            }else if type == "offlineCurriculum"{
//                //线下课
//                let vc = XS_KCXianxiaVC()
//                vc.id = id
//                navigationController?.pushViewController(vc, animated: true)
//            }else if type == "live"{
//                //直播课
//                let vc = XS_KCZhiboVC()
//                vc.id = id
//                navigationController?.pushViewController(vc, animated: true)
//            }
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        switch indexPath.section {
        case 0:
//            if XS_Singleton.shared.infoModel?.userBO != nil {
//                if XS_Singleton.shared.infoModel?.userBO.userTypeEnum() == XS_UserType.vip {
//                    return CGSize.init(width: .screenWidth - 32, height: 0)
//                }
//            }
            return CGSize.init(width: .screenWidth - 32, height: 122)
        case 1:
            return CGSize.init(width: .screenWidth - 32, height: 106)
        case 2:
            return CGSize.init(width: .screenWidth - 32, height: courseArray.count > 0 ? 94 : 260)
        case 3:
            return CGSize.init(width: .screenWidth - 32, height: courseRecordModel.records.count > 0 ? CGFloat(courseRecordModel.records.count) * (.scale * 104) + 1 : 260)
        default:
            return CGSize.init(width: 0, height: 0)
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        if section == 2 {
            return CGSize.init(width: .screenWidth, height: 50)
        }else if section == 3{
            return CGSize.init(width: .screenWidth, height: .scale * 114)
        }
        return CGSize.init(width: 0, height: 0)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
        if section == 3 {
            return CGSize(width: .screenWidth, height: 16)
        }
        return CGSize(width: 0, height: 0);
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        if section != 3 {
            if section == 2 {
                return .init(top: 0, left: 16, bottom: 8, right: 16)
            }
            return .init(top: 16, left: 16, bottom: 16, right: 16)
        }
        return .init(top: 0, left: 0, bottom: 0, right: 0)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        if section != 3 {
            if section == 2 {
                return 8
            }
            return 16
        }
        return 0
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        if section != 3 {
            return 16
        }
        return 0
    }
    
}

extension XS_PlanSubVC : JXSegmentedListContainerViewListDelegate{
    func listView() -> UIView {
        return view
    }
}

extension XS_PlanSubVC : XS_PlanTodayHeaderViewDelegate{
    func headerView(headerView: XS_PlanTodayHeaderView, didClickChangeBtn: UIButton) {
        let changeVC = XS_PlanChangeVC()
        navigationController?.pushViewController(changeVC, animated: true)
    }
}

extension XS_PlanSubVC : XS_GoalCertCellDelegate{
    func goalCertCell(goalCertCell: XS_GoalCertCell, didClickCourse: XS_CourseItemModel) {
        let type = didClickCourse.curriculumType
        let id = didClickCourse.id
        if type == "seriesCurriculum" || type == "notSeriesCurriculum" {
            //线上课
            let vc = XS_KeChengVC()
            vc.id = id
            navigationController?.pushViewController(vc, animated: true)
        }else if type == "offlineCurriculum"{
            //线下课
            let vc = XS_KCXianxiaVC()
            vc.id = id
            navigationController?.pushViewController(vc, animated: true)
        }else if type == "live"{
            //直播课
            let vc = XS_KCZhiboVC()
            vc.id = id
            navigationController?.pushViewController(vc, animated: true)
        }
    }
}

extension XS_PlanSubVC : XS_PlanCalendarCellDelegate{
    func calendarCell(calendarCell: XS_PlanCalendarCell, didSelectDate: CVCalendarDayView) {
        let date = didSelectDate.date.convertedDate() ?? Date.init()
        let dateFormatter = DateFormatter.init()
        dateFormatter.dateFormat = "yyyy-MM-dd"
        requestCourseTodayData(date: dateFormatter.string(from: date))
    }
}

extension XS_PlanSubVC : XS_PlanTodayItemCellDelegate{
    func todayItemCell(todayItemCell: XS_PlanTodayItemCell, didClickLearnBtn: UIButton) {
        let type = todayItemCell.model.curriculumType
        let id = todayItemCell.model.id
        if type == "seriesCurriculum" || type == "notSeriesCurriculum" {
            //线上课
            let vc = XS_KeChengVC()
            vc.id = id
            navigationController?.pushViewController(vc, animated: true)
        }else if type == "offlineCurriculum"{
            //线下课
            let vc = XS_KCXianxiaVC()
            vc.id = id
            navigationController?.pushViewController(vc, animated: true)
        }else if type == "live"{
            //直播课
            let vc = XS_KCZhiboVC()
            vc.id = id
            navigationController?.pushViewController(vc, animated: true)
        }
    }
    
    
}
